package cn.itcast.nio.c5;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.channels.CompletionHandler;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import static cn.itcast.nio.c1.ByteBufferUtil.debugAll;

/**
 * @Author: LDeng
 * @Date: 2021-05-17 11:25
 */
@Slf4j
public class AioFileChannel {

    public static void main(String[] args) {
        try (AsynchronousFileChannel channel =
                     AsynchronousFileChannel.open(Paths.get("1.txt"), StandardOpenOption.READ)) {
            //参数1： ByteBuffer
            //参数2： 读取起始位置
            //参数3： 附件
            //参数4： 回调对象
            ByteBuffer buffer = ByteBuffer.allocate(16);
            log.debug("read begin....");
            channel.read(buffer, 0, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                @Override //成功， attachement 将使用过的byteBuffer对象作为附件继续传递下去使用，
                public void completed(Integer result, ByteBuffer attachment) {
                    log.debug("read completed....{}",result);
                    attachment.flip();
                    debugAll(attachment);
                }

                @Override //失败
                public void failed(Throwable exc, ByteBuffer attachment) {
                    exc.printStackTrace();
                }
            });
            log.debug("read end....");
            System.in.read();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
